package com.winit.openapi.sms;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.winit.common.query.Page;
import com.winit.common.spi.SPIException;
import com.winit.common.spi.context.CommandContext;
import com.winit.erp.spi.bpartner.BpartnerService;
import com.winit.erp.spi.bpartner.vo.Bpartner;
import com.winit.openapi.constants.ApiConstant;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.sms.common.DateUtils;
import com.winit.openapi.sms.common.SmsUtils;
import com.winit.openapi.util.DateUtil;
import com.winit.sms.spi.common.vo.PageVo;
import com.winit.sms.spi.settlement.statement.StatementService;
import com.winit.sms.spi.settlement.statement.command.CreateStatementCommand;
import com.winit.sms.spi.settlement.statement.command.QueryStatementCommand;
import com.winit.sms.spi.settlement.statement.command.UpdateStatementCommand;
import com.winit.sms.spi.settlement.vo.StatementVo;
import com.winit.sms.spi.wallet.creditaccount.CreditCounterFeeService;
import com.winit.sms.spi.wallet.creditaccount.command.QueryCreditCounterFeeCommand;

/**
 * 卖家对帐单
 * 
 * @version <pre>
 * Author	Version		Date		Changes
 * 
 * </pre>
 * @since 1.
 */
@Controller
@RequestMapping("/sms/statement")
public class StatementController extends BaseController {

    private static Logger           logger = LoggerFactory.getLogger(StatementController.class);
    @Resource
    private StatementService        statementService;
    @Resource
    private BpartnerService         bpartnerService;
    @Resource
    private CreditCounterFeeService creditCounterFeeService;

    /**
     * 分页查询卖家对帐单
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     * @throws ParseException
     */
    @RequestMapping(value = "/pageStatement")
    public String pageStatement(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg)
                                                                                                               throws ParseException {
        QueryStatementCommand command = SmsUtils.toJavaObject(requestMsg.getData(), QueryStatementCommand.class);
        if (null != command.getEndDate()) {
            command.setEndDate(DateUtil.spliceDate(command.getEndDate()));
        }
        PageVo pageVo = SmsUtils.SetPageParams(requestMsg.getData());
        command.setPageVo(pageVo);
        Bpartner bpartner = CommandContext.getContext().get(ApiConstant.API_BPARTNER);
        if (bpartner == null) {
            logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>bpartner对象为空");
            return ERROR;
        }
        command.setPartnerCode(bpartner.getValue());
        if (null != command.getEndDate()) {
            command.setEndDate(DateUtil.spliceDate(command.getEndDate()));
        }
        try {
            Page<StatementVo> pageStatement = statementService.pageStatement(command);
            Iterator<StatementVo> it = pageStatement.iterator();
            while (it.hasNext()) {
                StatementVo statementVo = it.next();
                if (statementVo != null) {
                    //根据账期汇总手续费
                    QueryCreditCounterFeeCommand queryCreditCounterFeeCommand = new QueryCreditCounterFeeCommand();
                    queryCreditCounterFeeCommand.setCustomerCode(statementVo.getPartnerCode());
                    queryCreditCounterFeeCommand.setProductLine(statementVo.getProductLine());
                    queryCreditCounterFeeCommand.setCounterfeeDateStart(statementVo.getStartDate());
                    queryCreditCounterFeeCommand.setCounterfeeDateEnd(statementVo.getEndDate());
                    BigDecimal feeAmount = creditCounterFeeService.queryCreditCounterFeeTotal(queryCreditCounterFeeCommand);
                    statementVo.setFeeAmount(feeAmount == null ? BigDecimal.ZERO : feeAmount);
                }
            }

            Map<String, Object> data = SmsUtils.setPageData(pageStatement);
            responseMsg.setData(data);
        } catch (Exception e) {
            throw new ApiException(ErrorCode.SYSTEM_ERROR);
        }
        return SUCCESS;
    }

    /**
     * 按年查询帐单
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     * @throws ParseException
     */
    @RequestMapping(value = "/queryStatementByYear")
    public String pageStatementByYear(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg)
                                                                                                                     throws ParseException {
        QueryStatementCommand command = SmsUtils.toJavaObject(requestMsg.getData(), QueryStatementCommand.class);
        Bpartner bpartner = CommandContext.getContext().get(ApiConstant.API_BPARTNER);
        if (bpartner == null) {
            logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>bpartner对象为空");
            return ERROR;
        }
        command.setPartnerCode(bpartner.getValue());
        try {
            Page<StatementVo> pageStatement = statementService.pageStatement(command);
            List<String> yearList = new ArrayList<String>();
            List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
            for (StatementVo vo : pageStatement.getContent()) {
                String year = String.valueOf(DateUtils.getYear(vo.getStartDate()));
                Map<String, Object> tempMap = new HashMap<String, Object>();
                tempMap.put("END_DATE", vo.getEndDate());
                tempMap.put("START_DATE", vo.getStartDate());
                tempMap.put("YEAR", year);
                listMap.add(tempMap);
                if (!yearList.contains(year)) {
                    yearList.add(year);
                }
            }
            Map<String, Object> dataAll = new HashMap<String, Object>();
            List<Map<String, Object>> tmpListMapALL = new ArrayList<Map<String, Object>>();
            for (String year : yearList) {
                List<Map<String, Object>> tmpListMap = new ArrayList<Map<String, Object>>();
                for (Map<String, Object> map : listMap) {
                    if (year.equals(map.get("YEAR").toString())) {
                        tmpListMap.add(map);
                    }
                }
                dataAll.put("YEAR", year);
                dataAll.put("list", tmpListMap);
                tmpListMapALL.add(dataAll);
                dataAll = new HashMap<String, Object>();
            }
            responseMsg.setData(tmpListMapALL);
        } catch (Exception e) {
            throw new ApiException(ErrorCode.SYSTEM_ERROR);
        }
        return SUCCESS;
    }

    /**
     * 创建算定义帐单
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping("/createStatement")
    public String createStatement(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        try {
            CreateStatementCommand command = SmsUtils.toJavaObject(requestMsg.getData(), CreateStatementCommand.class);
            if (null != command.getEndDate()) {
                command.setEndDate(DateUtil.spliceDate(command.getEndDate()));
            }
            Bpartner bpartner = CommandContext.getContext().get(ApiConstant.API_BPARTNER);
            if (bpartner == null) {
                logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>bpartner对象为空");
                return ERROR;
            }
            command.setPartnerCode(bpartner.getValue());
            command.setPartnerName(bpartner.getName());
            statementService.createStatement(command);
            Map<String, Integer> data = new HashMap<String, Integer>();
            responseMsg.setData(data);
        } catch (Exception e) {
            logger.info("<======createStatement：", e);
            throw new ApiException(ErrorCode.SYSTEM_ERROR);
        }
        return SUCCESS;
    }

    /**
     * 生成电子发票
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping("/modifyStatementUrlById")
    public String modifyStatementUrlById(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        UpdateStatementCommand updateStatementCommand = new UpdateStatementCommand();
        try {
            updateStatementCommand = SmsUtils.toJavaObject(requestMsg.getData(), UpdateStatementCommand.class);
            CommandContext ctx = CommandContext.getContext();
            updateStatementCommand.setCtx(ctx);
            String url = statementService.modifyStatementUrlById(updateStatementCommand);
            responseMsg.setData(url);
        } catch (SPIException e) {
            logger.error("生成电子发票异常，ID:{},{}", updateStatementCommand.getId() + "", e.getMessage());
            responseMsg.setCode(e.getErrorCode());
            responseMsg.setMsg(e.getErrorMsg());
            return ERROR;
        }
        return SUCCESS;
    }
}
